//
//  NYHtmlHelper.m
//  NiuWaJiaoYu
//
//  Created by MinLison on 2018/1/4.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//

#import "NYHtmlHelper.h"
#import "NYPhotoBrowserViewController.h"
#import "UIImage+UrlSize.h"
@interface NYHtmlHelper ()
@property(nonatomic, weak) UIView * currentUsedView;
@property(nonatomic, assign) CGSize imgSize;
@end
@implementation NYHtmlHelper
- (CGSize)getAdjustImgSize:(CGSize)size
{
        CGFloat maxWidth = __MAIN_SCREEN_WIDTH__ - __WGWidth(40);
        CGFloat width = size.width;
        CGFloat height = size.height;
        
        if (width > maxWidth)
        {
                width = maxWidth;
                height = size.height * maxWidth / size.width;
        }
        return CGSizeMake(width, height);
        
}
- (NSString *)getImgSizeAndReplaceHtmlString:(NSString *)htmlString
{
        __block NSString *resString = htmlString.copy;
        [resString enumerateRegexMatches:@"<img(.*?)>" options:(0) usingBlock:^(NSString * _Nonnull match, NSRange matchRange, BOOL * _Nonnull stop) {
                if ([match rangeOfString:@"width"].location == NSNotFound && [match rangeOfString:@"http"].location != NSNotFound)
                {
                        [match enumerateRegexMatches:@"[a-zA-z]+://[^\\s]*" options:0 usingBlock:^(NSString * _Nonnull matchUrl, NSRange matchUrlRange, BOOL * _Nonnull urlStop) {
                                NSString *urlString = [matchUrl substringToIndex:matchUrl.length - 1];
                                CGSize imgSize = [self getAdjustImgSize:[UIImage getImageSizeWithURL:urlString]];
                                NSString *replaceString = [match stringByReplacingOccurrencesOfString:@"<img" withString:[NSString stringWithFormat:@"<img width=%d height=%d style=\"vertical-align:middle;\"",(int)imgSize.width,(int)imgSize.height]];
                                resString = [resString stringByReplacingOccurrencesOfString:match withString:replaceString];
                        }];
                        *stop = YES;
                        [self getImgSizeAndReplaceHtmlString:resString];
                }
        }];
        return resString;
}
- (NSArray *)getImageurlFromHtml:(NSString *)webString
{
        NSMutableArray * imageurlArray = @[].mutableCopy;
        
        //标签匹配
        NSString *parten = @"<img(.*?)>";
        NSError* error = NULL;
        NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:parten options:0 error:&error];
        
        NSArray* match = [reg matchesInString:webString options:0 range:NSMakeRange(0, [webString length] - 1)];
        
        for (NSTextCheckingResult * result in match) {
                
                //过去数组中的标签
                NSRange range = [result range];
                NSString * subString = [webString substringWithRange:range];
                
                
                //从图片中的标签中提取ImageURL
                NSRegularExpression *subReg = [NSRegularExpression regularExpressionWithPattern:@"http://(.*?)\"" options:0 error:NULL];
                NSArray* match = [subReg matchesInString:subString options:0 range:NSMakeRange(0, [subString length] - 1)];
                NSTextCheckingResult * subRes = match[0];
                NSRange subRange = [subRes range];
                subRange.length = subRange.length -1;
                NSString * imagekUrl = [subString substringWithRange:subRange];
                
                //将提取出的图片URL添加到图片数组中
                [imageurlArray addObject:imagekUrl];
        }
        return imageurlArray;
}
/// Public Mthoed
- (DTAttributedLabel *)createAttributedLabel
{
        DTAttributedLabel *dtAttrLabel = [[DTAttributedLabel alloc] init];
        dtAttrLabel.numberOfLines = 0;
        dtAttrLabel.delegate = self;
        dtAttrLabel.shouldDrawLinks = NO;
        dtAttrLabel.shouldDrawImages = YES;
        dtAttrLabel.shouldLayoutCustomSubviews = YES;
        dtAttrLabel.relayoutMask = DTAttributedTextContentViewRelayoutOnHeightChanged | DTAttributedTextContentViewRelayoutOnWidthChanged;
        self.currentUsedView = dtAttrLabel;
        return dtAttrLabel;
}
- (DTAttributedTextContentView *)createAttributedContentView
{
        DTAttributedTextContentView *dtAttrContentView = [[DTAttributedTextContentView alloc] init];
        dtAttrContentView.delegate = self;
        dtAttrContentView.shouldDrawLinks = NO;
        dtAttrContentView.shouldDrawImages = YES;
        dtAttrContentView.shouldLayoutCustomSubviews = YES;
        dtAttrContentView.relayoutMask = DTAttributedTextContentViewRelayoutOnHeightChanged | DTAttributedTextContentViewRelayoutOnWidthChanged;
        self.currentUsedView = dtAttrContentView;
        return dtAttrContentView;
}
- (DTAttributedTextView *)createAttributedTextView
{
        DTAttributedTextView *dtAttrTextView = [[DTAttributedTextView alloc] init];
        dtAttrTextView.textDelegate = self;
        dtAttrTextView.shouldDrawLinks = NO;
        dtAttrTextView.shouldDrawImages = YES;
        self.currentUsedView = dtAttrTextView;
        return dtAttrTextView;
}
- (NSAttributedString *)attributedStringForHtmlString:(NSString *)htmlString maxImageSize:(CGSize)maxImageSize imgSizeCallBackBlock:(NYHtmlHelperImgSizeChangeBlock)imgSizeCallBack
{
        self.imgSizeChangeBlock = imgSizeCallBack;
        if (NULLString(htmlString)) {
                return nil;
        }
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDidRelayoutSize:) name:DTAttributedTextContentViewDidFinishLayoutNotification object:self.currentUsedView];
        
        // Load HTML data
        NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
        
        // example for setting a willFlushCallback, that gets called before elements are written to the generated attributed string
        void (^callBackBlock)(DTHTMLElement *element) = ^(DTHTMLElement *element) {
                
                // the block is being called for an entire paragraph, so we check the individual elements
                
                for (DTHTMLElement *oneChildElement in element.childNodes)
                {
                        // if an element is larger than twice the font size put it in it's own block
                        if (oneChildElement.displayStyle == DTHTMLElementDisplayStyleInline && oneChildElement.textAttachment.displaySize.height > 2.0 * oneChildElement.fontDescriptor.pointSize)
                        {
                                oneChildElement.displayStyle = DTHTMLElementDisplayStyleBlock;
                                oneChildElement.paragraphStyle.minimumLineHeight = element.textAttachment.displaySize.height;
                                oneChildElement.paragraphStyle.maximumLineHeight = element.textAttachment.displaySize.height;
                        }
                }
        };
        UIFont *font = WGSystem13Font;
        NSMutableDictionary *options = [NSMutableDictionary dictionaryWithDictionary:@{
//                                                                                       NSTextSizeMultiplierDocumentOption : @(1),
                                                                                       DTMaxImageSize : [NSValue valueWithCGSize:maxImageSize],
                                                                                       DTDefaultFontFamily : font.familyName,
                                                                                       DTDefaultFontName : font.fontName,
                                                                                       DTDefaultFontSize : @(13),
                                                                                       DTDefaultLinkColor : UIColorHex(0x333333),
                                                                                       DTDefaultTextColor : UIColorHex(0x333333),
                                                                                       DTWillFlushBlockCallBack : callBackBlock,
                                                                                       }];
        NSAttributedString *string = [[NSAttributedString alloc] initWithHTMLData:data options:options documentAttributes:NULL];
        
        return string;
}
- (NSAttributedString *)attributedStringForHtmlString:(NSString *)htmlString maxImageSize:(CGSize)maxImageSize
{
        return [self attributedStringForHtmlString:htmlString maxImageSize:maxImageSize imgSizeCallBackBlock:nil];
}
- (void)linkPushed:(DTLinkButton *)button
{
        NSURL *URL = button.URL;
        
        if ([[UIApplication sharedApplication] canOpenURL:[URL absoluteURL]])
        {
                [[UIApplication sharedApplication] openURL:[URL absoluteURL]];
        }
}
- (void)tapGestureTaped:(UITapGestureRecognizer *)tapGesture
{

        UIImageView *imgView = (UIImageView *)tapGesture.view;
        [[NYPhotoBrowserViewController photoBrowserViewControllerWithImage:imgView.image] startPreviewFromRectInScreen:[imgView.superview convertRect:imgView.frame toView:nil]];

}
/// MARK: - DTCoreText delegate
- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame
{
        if ([attachment isKindOfClass:[DTImageTextAttachment class]])
        {
                // if the attachment has a hyperlinkURL then this is currently ignored
                DTLazyImageView *imageView = [[DTLazyImageView alloc] initWithFrame:frame];
                imageView.delegate = self;
                imageView.contentMode = UIViewContentModeScaleAspectFit;
                imageView.contentView = attributedTextContentView;
                
                // sets the image if there is one
                imageView.image = [(DTImageTextAttachment *)attachment image];
                
                // url for deferred loading
//                imageView.url = attachment.contentURL;
                if (attachment.contentURL) {
                        [imageView sd_setImageWithURL:attachment.contentURL placeholderImage:[UIImage selectionHolder]];
                }
#ifndef DEBUG
                // if there is a hyperlink then add a link button on top of this image
                if (attachment.hyperLinkURL)
                {
                        // NOTE: this is a hack, you probably want to use your own image view and touch handling
                        // also, this treats an image with a hyperlink by itself because we don't have the GUID of the link parts
                        imageView.userInteractionEnabled = YES;
                        
                        DTLinkButton *button = [[DTLinkButton alloc] initWithFrame:imageView.bounds];
                        button.URL = attachment.hyperLinkURL;
                        button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
                        button.GUID = attachment.hyperLinkGUID;
                        
                        // use normal push action for opening URL
                        [button addTarget:self action:@selector(linkPushed:) forControlEvents:UIControlEventTouchUpInside];
                        
                        [imageView addSubview:button];
                }
                else
                {
                        imageView.userInteractionEnabled = YES;
                        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureTaped:)];
                        [imageView addGestureRecognizer:tapGesture];
                }
#endif
                return imageView;
        }
        return nil;
}

/// MARK:  - DTLazyImageViewDelegate
//- (void)lazyImageView:(DTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size
//{
//        NSURL *url = lazyImageView.url;
//        CGSize imageSize = size;
//
//        NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
//
//        BOOL didUpdate = NO;
//
//        // update all attachments that match this URL (possibly multiple images with same size)
//        for (DTTextAttachment *oneAttachment in [lazyImageView.contentView.layoutFrame textAttachmentsWithPredicate:pred])
//        {
//                // update attachments that have no original size, that also sets the display size
//                if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero))
//                {
//                        oneAttachment.originalSize = imageSize;
//                        self.imgSize = imageSize;
//                        didUpdate = YES;
//                }
//        }
//
//        if (didUpdate)
//        {
//                // layout might have changed due to image sizes
//                // do it on next run loop because a layout pass might be going on
//                dispatch_async(dispatch_get_main_queue(), ^{
//                        lazyImageView.contentView.layouter = nil;
//                        [lazyImageView.contentView relayoutText];
//                });
//        }
//}
/// MARK: - Noti
- (void)viewDidRelayoutSize:(NSNotification *)noti
{
        if (noti.object != self.currentUsedView) {
                return;
        }
        if (self.imgSizeChangeBlock) {
                self.imgSizeChangeBlock(self.imgSize);
        }
}
@end
